<?php
namespace api\modules\v1\models\user;

use api\modules\v1\models\circle\Circle;
use api\modules\v1\models\userLevel\UserLevel;
use common\models\CacheKeys;
use common\models\friend\Friend;
use common\models\friend\FriendApply;
use common\models\Functions;
use common\models\Status;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

/**
 * Class UserLoginLog
 * @package api\modules\v1\models\employee
 */
class UserAttention extends \common\models\user\UserAttention
{

    /**
     * 关注
     * @return array
     */
    public function getFollow() {
        $trans = static::getDb()->beginTransaction();

        try {
            $userId = Yii::$app->request->post('user_id','');
            $type = Yii::$app->request->post('type','');
            if (!$userId) {
                throw new Exception('未知用户！');
            }
            if (empty($type)) {
                throw new Exception('未知类型！');
            }

            $userInfo = Yii::$app->getUser()->getIdentity()->toArray();

            CacheKeys::checkFrequency("FOLLOW_USER_".$userInfo['id'],1);
//            if($info['user_id'] != $user['id']) {
//                //是否是好友
//                $isFriendWhere = $isFriendAndWhere = [];
//                $isFriendWhere['user_id'] = $user['id'];
//                $isFriendWhere['friend_id'] = $info['user_id'];
//                $isFriend = Friend::getOneByWhere($isFriendWhere,'id');
//                if (empty($isFriend)) {
//                    throw new Exception('您和他不是好友，不能查看！');
//                }
//            }
            if($userInfo['id'] == $userId){
                throw new Exception('不能关注自己！');
            }
            $topicInfo = User::getOneInfoById($userId);
            if(empty($topicInfo)){
                throw new Exception('未知用户！');
            }
            $handleName = "关注";
            $data['topic_id'] = $userId;
            $data['user_id'] = $userInfo['id'];
            $data['type'] = $type;
            $check = static::getOneByWhere($data);
            if (!$check) {
                $data['create_time'] = date('Y-m-d H:i:s');
                $res = static::insertData($data);
                if ($res === false) {
                    throw new Exception('操作失败！');
                }

                if($type == Status::USER_ATTENTION_TYPE_FOLLOW){
                    $handleName = '关注';
                }
                if($type == Status::USER_ATTENTION_TYPE_STAR){
                    $handleName = '添加';
                }
                if($type == Status::USER_ATTENTION_TYPE_BLOCK){
                    $handleName = '拉黑';
//                    $friendModel = new Friend();
//                    $friendModel->delFriend($userInfo['user_id'],$topicInfo['friend_id'],$userInfo['user_tx_code'],$topicInfo['friend_tx_code']);
                }

                // 是否相互操作
                $checkTogether = static::getOneByWhere([
                    'topic_id' => $userInfo['id'],
                    'user_id' => $userId,
                    'type' => $type,
                ]);

                if ($checkTogether) {
                    static::updateData(['is_together' => Status::COMMON_RADIO_YES],['id' => [$res, $checkTogether['id']]]);

                    // 执行添加好友的操作
                    (new Friend()) -> addFriend($userInfo['id'],$userId, false);
                }

                $res = User::updateAllCounters(['attention_num' => 1], ['id' => $userInfo['id']]);
                $fans = User::updateAllCounters(['fans_num' => 1], ['id' => $topicInfo['id']]);
                if ($res == false || $fans == false) {
                    throw new Exception('操作失败！');
                }

            } else {
//                $res = static::deleteAll(['id' => $check['id']]);
//                if ($res === false) {
//                    throw new Exception('操作失败！');
//                }
//                if($type == Status::USER_ATTENTION_TYPE_FOLLOW){
//                    $handleName = '取消关注';
//                }
//                if($type == Status::USER_ATTENTION_TYPE_STAR){
//                    $handleName = '取消';
//                }
//                if($type == Status::USER_ATTENTION_TYPE_BLOCK){
//                    $handleName = '取消拉黑';
//                }
//
//                if ($userInfo['attention_num'] >= 1) {
//                    $res = User::updateAllCounters(['attention_num' => -1], ['id' => $userInfo['id']]);
//                    if ($res === false) {
//                        throw new Exception('操作失败！');
//                    }
//                }
//                if ($topicInfo['fans_num'] >= 1) {
//                    $fans = User::updateAllCounters(['fans_num' => -1], ['id' => $topicInfo['id']]);
//                    if ($fans == false) {
//                        throw new Exception('操作失败！');
//                    }
//                }

            }
            // 未读数量
            (new FriendApply())->notReadApplyNum($userId);

            $trans->commit();
            return Functions::formatRestAPI(0, $handleName.'成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    /**
     * 取消关注
     * @return array
     */
    public function cancelFollow() {
        $trans = static::getDb()->beginTransaction();

        try {
            $userId = Yii::$app->request->get('user_id','');
            $type = Yii::$app->request->get('type','');

//         Yii::info("用户ID".$userId);
//         Yii::info("类型".$type);
            if (!$userId) {
                throw new Exception('未知用户！');
            }
            if (empty($type)) {
                throw new Exception('未知类型！');
            }

            $userInfo = Yii::$app->getUser()->getIdentity()->toArray();

            CacheKeys::checkFrequency("CANCEL_FOLLOW_USER_".$userInfo['id'],1);
            if($userInfo['id'] == $userId){
                throw new Exception('不能关注自己！');
            }
            $topicInfo = User::getOneInfoById($userId);
            if(empty($topicInfo)){
                throw new Exception('未知用户！');
            }
            $handleName = "关注";
            if($type == Status::USER_ATTENTION_TYPE_FOLLOW){
                $handleName = '取消关注';
            }
            if($type == Status::USER_ATTENTION_TYPE_STAR){
                $handleName = '取消星标';
            }
            if($type == Status::USER_ATTENTION_TYPE_BLOCK){
                $handleName = '取消拉黑';
            }
            $data['topic_id'] = $userId;
            $data['user_id'] = $userInfo['id'];
            $data['type'] = $type;
            $check = static::getOneByWhere($data);
            if ($check) {
                $res = static::deleteAll(['id' => $check['id']]);
                if ($res === false) {
                    throw new Exception('操作失败！');
                }

                // 取消相互操作
                $checkTogether = static::getOneByWhere([
                    'topic_id' => $userInfo['id'],
                    'user_id' => $userId,
                    'type' => $type,
                ]);

                if ($checkTogether) {
                    static::updateData(['is_together' => Status::COMMON_RADIO_NO],['id' => [$check['id'], $checkTogether['id']]]);

                    # 判断是否是好友
                    //是否是好友
                    $isFriendWhere = $isFriendAndWhere = [];
                    $isFriendAndWhere[] = [
                        'or',
                        ['and',
                            ['=','user_id',$userId],
                            ['=','friend_id',$userInfo['id']],
                        ],
                        ['and',
                            ['=','user_id',$userInfo['id']],
                            ['=','friend_id',$userId],
                        ],
                    ];
                    $isFriend = Friend::getOneByAndWhere($isFriendWhere,$isFriendAndWhere,'id');
                    if ($isFriend) {
                        // 执行删除好友的操作
                        (new Friend()) -> delFriend($userInfo['id'],$userId, $userInfo['tx_code'],$topicInfo['tx_code']);
                    }

                }

                if ($userInfo['attention_num'] >= 1) {
                    $res = User::updateAllCounters(['attention_num' => -1], ['id' => $userInfo['id']]);
                    if ($res === false) {
                        throw new Exception('操作失败！');
                    }
                }
                if ($topicInfo['fans_num'] >= 1) {
                    $fans = User::updateAllCounters(['fans_num' => -1], ['id' => $topicInfo['id']]);
                    if ($fans == false) {
                        throw new Exception('操作失败！');
                    }
                }

                // 未读数量
                (new FriendApply())->notReadApplyNum($userId);
            }

            $trans->commit();
            return Functions::formatRestAPI(0, $handleName.'成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    /**
     * 感兴趣列表
     * @return array
     */
    public function getInterestList()
    {
        try {
            $page = (int) Yii::$app->request->get('page',1);
            $size = (int) Yii::$app->request->get('size',10);

            $userInfo = Yii::$app->getUser()->getIdentity()->toArray();

            $followIds = [];
            $followList = static::getByAndWhere(['user_id'=>$userInfo['id'],'type'=>Status::USER_ATTENTION_TYPE_FOLLOW]);
            $followIds = array_column($followList,'topic_id');
            array_push($followIds,$userInfo['id']);

            $where = $andWhere = [];
            $where['is_delete'] = Status::COMMON_RADIO_YES;
            $where['status'] = Status::COMMON_RADIO_YES;
            $andWhere = ['not in','id',$followIds];
//            $count = User::getCountByAndWhere($where,$andWhere);
//            $data = User::setPageinationAPI($page, $size, $count);

            $data = User::setPaginationForApi($page);
            $offset = ($page - 1) * $size;
            $list = User::getObjectByAndWhere($where,$andWhere,['id','login_name','user_face','nick_name','signature','fans_num'],'fans_num DESC', $offset, $size)
                ->asArray()->all();
//            var_dump($list);die;
            $result = [];
            foreach($list as $v){
                $result[] = [
                    'id' => (int) $v['id'],
                    'user_id' => $v['id'] ?: '',
                    'nick_name' => $v['nick_name'] ?? '',
                    'signature' => $v['signature'],
                    'face' => static::getAvatar($v['user_face']),
                    'num' => (int) $v['fans_num'],
                    'is_attention' => in_array($v['id'],$followIds),
                ];
            }

            $data['data'] = $result;
            return Functions::formatRestAPI(0, '', $data);
        }  catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch(Exception $e){
            return Functions::formatRestAPI($e->getCode() ? $e->getCode() : 1, $e->getMessage());
        }
    }


    /**
     * 关注和粉丝列表
     * @return array
     */
    public function getAttentionList()
    {
        try {
            $page = (int) Yii::$app->request->get('page',1);
            $size = (int) Yii::$app->request->get('size',10);
            $type = (int) Yii::$app->request->get('type','');
            $attentionType= (int) Yii::$app->request->get('attention_type','');
            $code = Yii::$app->request->get('code','');
            //类型  1：关注  2：粉丝
            $userInfo = Yii::$app->getUser()->getIdentity()->toArray();
            $levelInfo = UserLevel::getOneByWhere(['id' => $userInfo['level_id']]);
            $userId = $userInfo['id'];

            if($code){
                $viewUser = User::getOneByWhere(['tx_code'=>$code]);
                $userId = $viewUser['id'];
                if(empty($viewUser)){
                    throw new Exception('未知用户');
                }
            }

            $where = $andWhere = [];
            if($type == 1){
                $where['user_id'] = $userId;
            }else if($type == 2){
                $where['topic_id'] = $userId;
            }else{
                throw new Exception('类型错误！');
            }

            //关注type 1
            $where['type'] = $attentionType;
            if ($attentionType == Status::USER_ATTENTION_TYPE_FOLLOW) {
                $where['is_together'] = Status::COMMON_RADIO_NO;
            }

//            $count = static::getCountByAndWhere($where,$andWhere);
//            $data = static::setPageinationAPI($page, $size, $count);

            $data = static::setPaginationForApi($page);

            $offset = ($page - 1) * $size;

//            $longitude = $this->getLongitude() ? $this->getLongitude() : '116.3424590000';
//            $latitude = $this->getLatitude() ? $this->getLatitude() : '39.91024';
            list($longitude,$latitude) = $this->getPosition($userInfo['phone']);

            $list = static::getObjectByAndWhere($where, $andWhere, ['*'], 'is_read DESC, id DESC', $offset, $size)
                ->with([
                    'user' => function ($q) use ($longitude, $latitude) {
                    $distanceField = "ROUND(
                        6378.138 * 2 * ASIN(
                            SQRT(
                                POW(
                                    SIN(
                                        (
                                            {$latitude} * PI() / 180 - latitude * PI() / 180
                                        ) / 2
                                    ),
                                    2
                                ) + COS({$latitude} * PI() / 180) * COS(latitude * PI() / 180) * POW(
                                    SIN(
                                        (
                                            {$longitude} * PI() / 180 - longitude * PI() / 180
                                        ) / 2
                                    ),
                                    2
                                )
                            )
                        ),5 
                    ) AS distance";
                    $q -> select(['id','nick_name','tx_code','signature','user_face','latitude','longitude','is_hiding',$distanceField]);
                },
                    'topic' => function ($q) use ($longitude, $latitude) {
                        $distanceField = "ROUND(
                        6378.138 * 2 * ASIN(
                            SQRT(
                                POW(
                                    SIN(
                                        (
                                            {$latitude} * PI() / 180 - latitude * PI() / 180
                                        ) / 2
                                    ),
                                    2
                                ) + COS({$latitude} * PI() / 180) * COS(latitude * PI() / 180) * POW(
                                    SIN(
                                        (
                                            {$longitude} * PI() / 180 - longitude * PI() / 180
                                        ) / 2
                                    ),
                                    2
                                )
                            )
                        ),5 
                    ) AS distance";
                        $q -> select(['id','nick_name','tx_code','signature','user_face','is_hiding',$distanceField]);
                    }
                ])
                ->asArray()->all();
            //关注的人
            $followList = static::getByAndWhere(['user_id'=>$userId,'type'=>$attentionType]);
            $followIds = array_column($followList,'topic_id');

            $result = [];
            foreach ($list as $v) {
                $singleUserInfo = ArrayHelper::getValue($v,'user',[]);
                $singleTopicInfo = ArrayHelper::getValue($v,'topic',[]);


                if($type == 1){
                    $distance = User::handleDistance($levelInfo, $singleTopicInfo, round($singleTopicInfo['distance'],2));


//                    $distance = round($singleTopicInfo['distance'],2).'KM';
//                    if($levelInfo['show_nearby'] == Status::COMMON_RADIO_NO){
//                        $distance = ">100KM";
//                    }
                    //关注
                    $result[] = [
                        'id' => (int) $v['id'],
                        'user_id' => $singleTopicInfo['id'] ?: '',
                        'tx_code' => $singleTopicInfo['tx_code'] ?: '',
                        'nick_name' => $singleTopicInfo['nick_name'] ?? '',
                        'signature' => $singleTopicInfo['signature'],
                        'face' => static::getAvatar($singleTopicInfo['user_face']),
                        'time' => strtotime($v['create_time']),
                        'is_attention' => in_array($v['topic_id'],$followIds),
                        'distance' => $distance,
                    ];
                }
                if($type == 2){
                    $distance = User::handleDistance($levelInfo, $singleUserInfo, round($singleUserInfo['distance'],2));

//                    $distance = round($singleUserInfo['distance'],2).'KM';
//                    if($levelInfo['show_nearby'] == Status::COMMON_RADIO_NO ){
//                        $distance = ">100KM";
//                    }

                    $result[] = [
                        'id' => (int) $v['id'],
                        'user_id' => $singleUserInfo['id'] ?: '',
                        'tx_code' => $singleUserInfo['tx_code'] ?: '',
                        'nick_name' => $singleUserInfo['nick_name'] ?? '',
                        'signature' => $singleUserInfo['signature'],
                        'face' => static::getAvatar($singleUserInfo['user_face']),
                        'time' => strtotime($v['create_time']),
                        'is_attention' => in_array($v['user_id'],$followIds),
                        'distance' => $distance,
                    ];
                }
            }

            if($type == 2){
                # 设为已读
                static::updateData(['is_read' => Status::COMMON_RADIO_YES],['id' => ArrayHelper::getColumn($list,'id')]);
                // 未读数量
                (new FriendApply())->notReadApplyNum($userId);
            }

            $data['data'] = $result;
            return Functions::formatRestAPI(0, '', $data);
        }  catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch(Exception $e){
            return Functions::formatRestAPI($e->getCode() ? $e->getCode() : 1, $e->getMessage());
        }
    }

}
